package com.linktrip.devicemanager.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.linktrip.devicemanager.entity.DeviceInfo;

/**
 * @author CaineZhu E-mail: CaineZhu@me.com
 * @version 创建时间：2017年3月17日 下午5:48:42
 * @类说明 http 请求类
 */

public class HttpUtil {

	static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	public static String httpUrlConnection(String url, String _method, String params) {
		StringBuilder result = new StringBuilder();
		try {

			if ("GET".equalsIgnoreCase(_method)) {
				if (!ToolKits.isEmpty(params))
					url = url + "?" + params;
			}

			// 建立连接
			URL pathUrl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) pathUrl.openConnection();

			// //设置连接属性
			httpConn.setDoOutput(true);// 使用 URL 连接进行输出
			httpConn.setDoInput(true);// 使用 URL 连接进行输入
			httpConn.setUseCaches(false);// 忽略缓存
			if ("POST".equalsIgnoreCase(_method)) {
				httpConn.setRequestMethod(_method);// 设置URL请求方法

				// 设置请求属性
				// 获得数据字节数据，请求数据流的编码，必须和下面服务器端处理请求流的编码一致
				byte[] requestStringBytes = params.getBytes("UTF-8");
				httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				// httpConn.setRequestProperty("Connection", "Keep-Alive");//
				// 维持长连接
				httpConn.setRequestProperty("Charset", "UTF-8");

				// 建立输出流，并写入数据
				OutputStream outputStream = httpConn.getOutputStream();
				outputStream.write(requestStringBytes);
				outputStream.close();
			}
			// 获得响应状态
			int responseCode = httpConn.getResponseCode();

			if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功
				// 当正确响应时处理数据
				String readLine;
				BufferedReader responseReader;
				// 处理响应流，必须与服务器响应流输出的编码一致
				responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					result.append(readLine).append("\n");
				}
				responseReader.close();
				// System.out.println(sb.toString());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		logger.info("result:{}", result);
		return result.toString();
	}

	public static String httpUrlConnectionForJson(String url, String _method, String params, String authorization) {
		StringBuilder result = new StringBuilder();
		try {

			if ("GET".equalsIgnoreCase(_method)) {
				if (!ToolKits.isEmpty(params))
					url = url + "?" + params;
			}

			// 建立连接
			URL pathUrl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) pathUrl.openConnection();

			// //设置连接属性
			httpConn.setDoOutput(true);// 使用 URL 连接进行输出
			httpConn.setDoInput(true);// 使用 URL 连接进行输入
			httpConn.setUseCaches(false);// 忽略缓存
			httpConn.setConnectTimeout(2000);
			httpConn.setRequestProperty("Content-Type", "application/json");
			if (!ToolKits.isEmpty(authorization))
				httpConn.setRequestProperty("Authorization", authorization);
			// httpConn.setRequestProperty("Connection", "Keep-Alive");//
			// 维持长连接
			httpConn.setRequestProperty("Charset", "UTF-8");
			if ("POST".equalsIgnoreCase(_method)) {
				httpConn.setRequestMethod(_method);// 设置URL请求方法

				// 设置请求属性
				// 获得数据字节数据，请求数据流的编码，必须和下面服务器端处理请求流的编码一致
				byte[] requestStringBytes = params.getBytes("UTF-8");

				// 建立输出流，并写入数据
				OutputStream outputStream = httpConn.getOutputStream();
				outputStream.write(requestStringBytes);
				outputStream.close();
			}
			// 获得响应状态
			int responseCode = httpConn.getResponseCode();

			if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功
				// 当正确响应时处理数据
				String readLine;
				BufferedReader responseReader;
				// 处理响应流，必须与服务器响应流输出的编码一致
				responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					result.append(readLine).append("\n");
				}
				responseReader.close();
				// System.out.println(sb.toString());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		//logger.info("result:{}", result);
		return result.toString();
	}

	public static void callbackData(String url, String _method, String params, String authorization) {

		try {

			if ("GET".equalsIgnoreCase(_method)) {
				if (!ToolKits.isEmpty(params))
					url = url + "?" + params;
			}

			// 建立连接
			URL pathUrl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) pathUrl.openConnection();

			// //设置连接属性
			httpConn.setDoOutput(true);// 使用 URL 连接进行输出
			httpConn.setDoInput(true);// 使用 URL 连接进行输入
			httpConn.setUseCaches(false);// 忽略缓存
			httpConn.setConnectTimeout(1000);
			httpConn.setRequestProperty("Content-Type", "application/json");
			if (!ToolKits.isEmpty(authorization))
				httpConn.setRequestProperty("Authorization", authorization);
			// httpConn.setRequestProperty("Connection", "Keep-Alive");//
			// 维持长连接
			httpConn.setRequestProperty("Charset", "UTF-8");
			if ("POST".equalsIgnoreCase(_method)) {
				httpConn.setRequestMethod(_method);// 设置URL请求方法

				// 设置请求属性
				// 获得数据字节数据，请求数据流的编码，必须和下面服务器端处理请求流的编码一致
				byte[] requestStringBytes = params.getBytes("UTF-8");

				// 建立输出流，并写入数据
				OutputStream outputStream = httpConn.getOutputStream();
				outputStream.write(requestStringBytes);
				outputStream.close();
			}
			// 获得响应状态
			// int responseCode = httpConn.getResponseCode();
			// logger.info("response code:{}",responseCode);
			logger.info("response code:{}", "callback done.");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.info("response error:{}", ex.getMessage());
		}
		// logger.info("result:{}", result);
		// return result.toString();
	}

	public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
		// TODO Auto-generated method stub
		for(int j=0;j<10;j++){
			Thread.sleep(5000);
			System.out.println();
			System.out.println("======================="+j+"=========================");
		for (int i = 0; i < 100; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					String url = "http://localhost:8080/base/api/callback2";
					String result = httpUrlConnectionForJson(url, "POST", "haha", null);
				}
			}).start();
			
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					DeviceInfo info = new DeviceInfo();
					info.setDevice_no("QWERT");
					String param = JSONObject.toJSONString(info);
					String url2 = "http://localhost:8080/base/api/callback";
					String result2 = HttpUtil.httpUrlConnectionForJson(url2, "POST", param, null);
				}
			}).start();
			
		}
		// System.out.println(result);
		System.out.println("================================================");
		System.out.println();
	}
		
	}
}
